package jupiter.servlets;


import javax.jms.*;

import jupiter.messaging.Message;
import jupiter.util.Timey;


import org.apache.activemq.command.*;
import org.apache.activemq.util.ByteSequence;
import org.json.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MessageEventListener  implements MessageListener {

	Logger logger = LoggerFactory.getLogger(MessageEventListener.class);
	public void onMessage(javax.jms.Message msg) {
		  try {
			  String m = "";
			  if(msg==null)
			    logger.info("Message: message null");
			  else {
			    if(msg instanceof ObjectMessage) {
			        m = (String) ((ObjectMessage)msg).getObject();
			    } else if(msg instanceof TextMessage) {
			        m = ((TextMessage)msg).getText();
			    } else {
			        ActiveMQBytesMessage bytes_message = (ActiveMQBytesMessage)msg;
			        ByteSequence sequence = bytes_message.getContent();

			        for(int i=0; i < sequence.getData().length; i++) {
			            m += (char)sequence.getData()[i];
			        }
			    }
			  }
		        Message message = new Message(m);
		        if(message.type.equals("admin")){
		        	message.filter();
		        }
		        message.putInInboxes();
			}catch(RuntimeException e){
				logger.error("RuntimeException in MessageEventListener", e);
				throw e;
		    }catch(Exception e){
				logger.error("Exception in MessageEventListener", e);
		    }
	}

}
